<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="ConcurrentLinkedQueue，基于链表的无界的线程安全队列。  当许多线程将共享对公共集合的访问时， ConcurrentLinkedQueue是合适的选择。 像大多数其他并发集合实现一样，此类不允许使用null元素。 此实现采用了一种高效的非阻塞算法，该算法基于 Maged M. Michael 和 Michael L. Scott 在《Simple、Fast、Practical">
<meta property="og:type" content="article">
<meta property="og:title" content="ConcurrentLinkedQueue源码分析">
<meta property="og:url" content="http://example.com/2021/12/15/ConcurrentLinkedQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="ConcurrentLinkedQueue，基于链表的无界的线程安全队列。  当许多线程将共享对公共集合的访问时， ConcurrentLinkedQueue是合适的选择。 像大多数其他并发集合实现一样，此类不允许使用null元素。 此实现采用了一种高效的非阻塞算法，该算法基于 Maged M. Michael 和 Michael L. Scott 在《Simple、Fast、Practical">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-12-14T16:24:43.000Z">
<meta property="article:modified_time" content="2021-12-14T16:33:36.715Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="JUC">
<meta property="article:tag" content="并发集合类">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/12/15/ConcurrentLinkedQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/12/15/ConcurrentLinkedQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/","path":"2021/12/15/ConcurrentLinkedQueue源码分析/","title":"ConcurrentLinkedQueue源码分析"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>ConcurrentLinkedQueue源码分析 | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/12/15/ConcurrentLinkedQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="ConcurrentLinkedQueue源码分析 | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ConcurrentLinkedQueue源码分析
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-12-15 00:24:43 / 修改时间：00:33:36" itemprop="dateCreated datePublished" datetime="2021-12-15T00:24:43+08:00">2021-12-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/JUC/" itemprop="url" rel="index"><span itemprop="name">JUC</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p><code>ConcurrentLinkedQueue</code>，<strong>基于链表的无界的线程安全队列</strong>。</p>
<p> 当许多线程将共享对公共集合的访问时， ConcurrentLinkedQueue是合适的选择。 <strong>像大多数其他并发集合实现一样，此类不允许使用null元素</strong>。</p>
<p>此实现采用了一种高效的非阻塞算法，该算法基于 Maged M. Michael 和 Michael L. Scott 在《Simple、Fast、Practical Non-Blocking and Blocking Concurrent Queue Algorithms》 中描述的算法 。</p>
<p><strong>迭代器是弱一致性的，返回元素反映了在迭代器创建时或之后的某个时刻的队列状态</strong>。 </p>
<p>它们不会抛出 <code>java.util.ConcurrentModificationException</code> ，并且可能与其他操作同时进行。</p>
<p>自迭代器创建以来队列中包含的元素将只返回一次。</p>
<p>某个迭代器创建之后，使用它遍历队列元素时，队列中的某个元素正好返回一次。</p>
<p>请注意，与大多数集合不同， size方法不是时间复杂度为O(1)的操作。</p>
<p> 由于这些队列的异步性质，确定当前元素数量需要遍历元素（所以它的时间复杂度是O(n) ，需要我们注意），因此如果在遍历期间修改此集合，则可能会报告不准确的结果。</p>
<p>此外，批量操作addAll 、 removeAll 、 retainAll 、 containsAll 、 equals和toArray不能保证以原子方式执行。 </p>
<p>内存一致性影响：与其他并发集合一样，在一个线程中将对象放入ConcurrentLinkedQueue中的操作发生在另一个线程中从ConcurrentLinkedQueue访问或删除该元素之后的操作之前。</p>
<p>请注意，与此包中的大多数非阻塞算法一样，此实现依赖于以下事实：<br>在垃圾中收集到的系统中，不存在ABA问题的可能性。<br>要回收节点，则无需使用“计数指针”或其他相关技术。</p>
<p>基本的循环不变量:</p>
<ul>
<li>有且仅有一个节点的后即指针为null，就是队列的最后一个节点</li>
<li>CAS一个节点的引用和null引用，可以原子性地将它从队列中移除。</li>
<li>从head节点出发遍历所有元素的可达性必须保持，即使在并发修改的情况下。 </li>
<li>一个已经出队的节点仍然可能处于可使用状态，比如在发生<strong>创建一个迭代器</strong>或者<strong>使用poll</strong>(不过它暂时失去了cpu时间片)的情况时。</li>
</ul>
<p>一个优化，每当当前指针距离头&#x2F;尾指针两步远时候，都会去更新 head &#x2F; tail。</p>
<p>因为头尾节点都是并发并且独立地更新的，所以完全由可能一方落后于另一方更新。</p>
<p>头部和尾部都有可能滞后，</p>
<p>迭代器会跳过元素为null的节点。</p>
<p>当创造一个节点（入队操作前）的时候，为了避免 volatile 写的开销，</p>
<p>使用了 Unsafe.putObject 代替了普通写，是的排队的开销降为约1.5倍的CAS。</p>
<p>头部和尾部节点有可能引用，也有可能不引用一个有着非空项的节点。</p>
<p>如果队列是空的，那么所有元素必然都是空的。</p>
<p>创建节点时，头尾节点引用一个有着空元素的哑结点。</p>
<p>它们都使用CAS进行更新，所以永不倒回。</p>
<p>注：为了节省篇幅，略去部分方法以及注释。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> java.util.concurrent;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConcurrentLinkedQueue</span>&lt;E&gt; <span class="keyword">extends</span> <span class="title class_">AbstractQueue</span>&lt;E&gt;</span><br><span class="line">        <span class="keyword">implements</span> <span class="title class_">Queue</span>&lt;E&gt;, java.io.Serializable &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> <span class="variable">serialVersionUID</span> <span class="operator">=</span> <span class="number">196745693267521676L</span>;</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">Node</span>&lt;E&gt; &#123;</span><br><span class="line">        <span class="keyword">volatile</span> E item;</span><br><span class="line">        <span class="keyword">volatile</span> Node&lt;E&gt; next;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * Constructs a new node.  Uses relaxed write because item can</span></span><br><span class="line"><span class="comment">         * only be seen after publication via casNext.</span></span><br><span class="line"><span class="comment">         * 创建一个节点，使用unsafe的方式，不过在使用 casNext 后才能真正遍历到它。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        Node(E item) &#123;</span><br><span class="line">            UNSAFE.putObject(<span class="built_in">this</span>, itemOffset, item);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">boolean</span> <span class="title function_">casItem</span><span class="params">(E cmp, E val)</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> UNSAFE.compareAndSwapObject(<span class="built_in">this</span>, itemOffset, cmp, val);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">      	<span class="comment">//  t.lazySetNext(newNode) &lt;==&gt; t.next = newNode</span></span><br><span class="line">        <span class="keyword">void</span> <span class="title function_">lazySetNext</span><span class="params">(Node&lt;E&gt; val)</span> &#123;</span><br><span class="line">            UNSAFE.putOrderedObject(<span class="built_in">this</span>, nextOffset, val); </span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">boolean</span> <span class="title function_">casNext</span><span class="params">(Node&lt;E&gt; cmp, Node&lt;E&gt; val)</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> UNSAFE.compareAndSwapObject(<span class="built_in">this</span>, nextOffset, cmp, val);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Unsafe mechanics</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> sun.misc.Unsafe UNSAFE;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> itemOffset;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> nextOffset;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                UNSAFE = sun.misc.Unsafe.getUnsafe();</span><br><span class="line">                Class&lt;?&gt; k = Node.class;</span><br><span class="line">                itemOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                    (k.getDeclaredField(<span class="string">&quot;item&quot;</span>));</span><br><span class="line">                nextOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                    (k.getDeclaredField(<span class="string">&quot;next&quot;</span>));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 不变量:</span></span><br><span class="line"><span class="comment">     * - 所有存活节点都可以通过 head 节点到达，通过后继指针 </span></span><br><span class="line"><span class="comment">     * - head != null</span></span><br><span class="line"><span class="comment">     * - (tmp = head).next != tmp || tmp != head  ???</span></span><br><span class="line"><span class="comment">     * 非不变量:</span></span><br><span class="line"><span class="comment">     * - head.item 可能为null，也有可能不为null,</span></span><br><span class="line"><span class="comment">		 * - 允许 tail 到 head的滞后，也就是可能无法从 head 到达 tail.</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">volatile</span> Node&lt;E&gt; head;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 不变量:</span></span><br><span class="line"><span class="comment">     * - the last node 总是可以通过 tail 节点到达，通过后继指针 （the last node 是唯一的其next值为 null 的 node）</span></span><br><span class="line"><span class="comment">     * - tail != null</span></span><br><span class="line"><span class="comment">     * 非不变量:</span></span><br><span class="line"><span class="comment">     * - tail.item 可能为null，也有可能不为null,</span></span><br><span class="line"><span class="comment">		 * - 允许 tail 到 head的滞后，也就是可能无法从 head 到达 tail.</span></span><br><span class="line"><span class="comment">     * - tail.next 可能也可能不”自我指向“ tail.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">volatile</span> Node&lt;E&gt; tail;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 空队列，head、tail 指向同一哑结点</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ConcurrentLinkedQueue</span><span class="params">()</span> &#123;</span><br><span class="line">        head = tail = <span class="keyword">new</span> <span class="title class_">Node</span>&lt;E&gt;(<span class="literal">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ConcurrentLinkedQueue</span><span class="params">(Collection&lt;? extends E&gt; c)</span> &#123;</span><br><span class="line">        Node&lt;E&gt; h = <span class="literal">null</span>, t = <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">for</span> (E e : c) &#123;</span><br><span class="line">            checkNotNull(e); <span class="comment">// 注意 ConcurrentLinkedQueue 不允许null元素</span></span><br><span class="line">            Node&lt;E&gt; newNode = <span class="keyword">new</span> <span class="title class_">Node</span>&lt;E&gt;(e);</span><br><span class="line">            <span class="keyword">if</span> (h == <span class="literal">null</span>) <span class="comment">// 遇到第一个元素</span></span><br><span class="line">                h = t = newNode; </span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                t.lazySetNext(newNode); <span class="comment">// 相当于 t.next = newNode, 不过避免了 volatile 写</span></span><br><span class="line">                t = newNode;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (h == <span class="literal">null</span>) <span class="comment">// c 为 empty，同上</span></span><br><span class="line">            h = t = <span class="keyword">new</span> <span class="title class_">Node</span>&lt;E&gt;(<span class="literal">null</span>);</span><br><span class="line">        head = h;</span><br><span class="line">        tail = t;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Tries to CAS head to p. If successful, repoint old head to itself</span></span><br><span class="line"><span class="comment">     * as sentinel for succ(), below.</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * CAS替换掉旧 head （h）为 新 head（p）</span></span><br><span class="line"><span class="comment">     * 如果替换成功，旧 head的next指针指向自己，成为哨兵</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">updateHead</span><span class="params">(Node&lt;E&gt; h, Node&lt;E&gt; p)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (h != p &amp;&amp; casHead(h, p))</span><br><span class="line">            h.lazySetNext(h); <span class="comment">// 使旧head的后继为head自己，起哨兵作用</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Returns the successor of p, or the head node if p.next has been</span></span><br><span class="line"><span class="comment">     * linked to self, which will only be true if traversing with a</span></span><br><span class="line"><span class="comment">     * stale pointer that is now off the list.</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * 获取 p 的后继，不过如果 p.next == p 的话，说明 p 已经出队了</span></span><br><span class="line"><span class="comment">     *（p.next == p 就是我们设置的标志，见h.lazySetNext(h)，</span></span><br><span class="line"><span class="comment">     * 因为正常情况下不会出现这种情况 —— 正常情况下 p.next == p 说明链表成环） </span></span><br><span class="line"><span class="comment">     * 此时返回链表新的 head，表示从新头出发</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">final</span> Node&lt;E&gt; <span class="title function_">succ</span><span class="params">(Node&lt;E&gt; p)</span> &#123;</span><br><span class="line">        Node&lt;E&gt; next = p.next;</span><br><span class="line">        <span class="keyword">return</span> (p == next) ? head : next;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Inserts the specified element at the tail of this queue.</span></span><br><span class="line"><span class="comment">     * As the queue is unbounded, this method will never return &#123;<span class="doctag">@code</span> false&#125;.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> &#123;<span class="doctag">@code</span> true&#125; (as specified by &#123;<span class="doctag">@link</span> Queue#offer&#125;)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> NullPointerException if the specified element is null</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">offer</span><span class="params">(E e)</span> &#123;</span><br><span class="line">        checkNotNull(e);</span><br><span class="line">        <span class="keyword">final</span> Node&lt;E&gt; newNode = <span class="keyword">new</span> <span class="title class_">Node</span>&lt;E&gt;(e);</span><br><span class="line"></span><br><span class="line">      	<span class="comment">// 无界队列，一定可以插入队尾成功。所以，如果失败，一直重试下去</span></span><br><span class="line">        <span class="keyword">for</span> (Node&lt;E&gt; t = tail, p = t;;) &#123;</span><br><span class="line">            Node&lt;E&gt; q = p.next;</span><br><span class="line">            <span class="keyword">if</span> (q == <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="comment">// p is last node</span></span><br><span class="line">                <span class="keyword">if</span> (p.casNext(<span class="literal">null</span>, newNode)) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (p != t) <span class="comment">// p == t的时候不更新（防止每一次入队操作都去更新tail，间隔一次）</span></span><br><span class="line">                        casTail(t, newNode);  <span class="comment">// 失败也ok</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// CAS竞争失败，下次再读，再去尝试</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (p == q) <span class="comment">// 只有一种情况出现 p == q, 就是 p 这个节点作为旧 head 从队列中被剔除出去，用 p.next = p 标识</span></span><br><span class="line">              </span><br><span class="line">                <span class="comment">// We have fallen off list.  If tail is unchanged, it</span></span><br><span class="line">                <span class="comment">// will also be off-list, in which case we need to</span></span><br><span class="line">                <span class="comment">// jump to head, from which all live nodes are always</span></span><br><span class="line">                <span class="comment">// reachable.  Else the new tail is a better bet.</span></span><br><span class="line">              	<span class="comment">// -------- 以上为源码注释 ---------</span></span><br><span class="line">                p = (t != (t = tail)) ? t : head; </span><br><span class="line">                <span class="comment">// 首先，跳到 head 处肯定是正确的，无非可能要多做几次循环找到尾节点罢了。</span></span><br><span class="line">                <span class="comment">// 其次，如果 tail 发生了变化，说明有其他线程入队了节点，并且成功修改了 tail，这个时候没必要从 head 出发,</span></span><br><span class="line">                <span class="comment">// 新的 tail 是更好的选择。</span></span><br><span class="line">          		  <span class="comment">// </span></span><br><span class="line">                <span class="comment">// 需要特别指明的是，如果 p 都已经出队了，那么 t 肯定也出队了（因为 p 是从 t 出发的嘛）</span></span><br><span class="line">                <span class="comment">// 如果说此时 tail 还没有发生变化，说明此时 tail 已经跑到了 head的前面（这是完全可能发生的）</span></span><br><span class="line">                <span class="comment">// 这时就必须跳到head了重新出发了。</span></span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                <span class="comment">// 寻找真正的”尾节点“</span></span><br><span class="line">                p = (p != t &amp;&amp; t != (t = tail)) ? t : q; </span><br><span class="line">                <span class="comment">/* </span></span><br><span class="line"><span class="comment">                 * 这个三元表达式，做了很多事，有判断，有赋值。</span></span><br><span class="line"><span class="comment">                 * 如果，改写成下面这样，行不行呢？</span></span><br><span class="line"><span class="comment">                 * t = tail; p = q;</span></span><br><span class="line"><span class="comment">                 * 我觉得也是没问题的，因为这是个LIFO的队列，p 不是 the last node，顺着往下找就是了.</span></span><br><span class="line"><span class="comment">                 * 不过作者认为，如果经过一次循环后（也就是 p 跳过一个节点之后,此时 p != t，如果又 tail发生了变化，</span></span><br><span class="line"><span class="comment">                 * 直接跳到新的 tail 处继续寻找更好）</span></span><br><span class="line"><span class="comment">                 */</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * 这段逻辑和上面的offer（入队）差不多：</span></span><br><span class="line"><span class="comment">     * 1. 找到链表的真正的头结点（从 head 出发，找到第一个 item 不为null的节点）</span></span><br><span class="line"><span class="comment">     * 2. 将头结点出队（cas将item域置null）</span></span><br><span class="line"><span class="comment">     * 3. 更新 head （cas更新head，旧head标记为&quot;哨兵“）</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> E <span class="title function_">poll</span><span class="params">()</span> &#123;</span><br><span class="line">        restartFromHead:</span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; h = head, p = h, q;;) &#123;</span><br><span class="line">                <span class="type">E</span> <span class="variable">item</span> <span class="operator">=</span> p.item;</span><br><span class="line">              </span><br><span class="line">                <span class="comment">// item 不为 null，说明 p 就是链表的头结点了</span></span><br><span class="line">                <span class="keyword">if</span> (item != <span class="literal">null</span> &amp;&amp; p.casItem(item, <span class="literal">null</span>)) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (p != h) <span class="comment">// 和跟新tail一样，不要每次出队一个节点，就更新一下 head（宁可多循环几次去找到真正的头结点）</span></span><br><span class="line">                        updateHead(h, ((q = p.next) != <span class="literal">null</span>) ? q : p);</span><br><span class="line">                    <span class="keyword">return</span> item;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> ((q = p.next) == <span class="literal">null</span>) &#123; <span class="comment">// p的item为null，p 又没有next节点，说明队列此时已经为empty了，返回null即可</span></span><br><span class="line">                    updateHead(h, p); <span class="comment">// 更新 head </span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (p == q)</span><br><span class="line">                    <span class="comment">// 和上面的一样，如果有其他 thread 也在 poll 节点的话，那么 p 引用的节点可能已经出队，标记为哨兵（哨兵的next指针指向自己）</span></span><br><span class="line">                    <span class="comment">// 这个时候需要从新的 head 出发寻找</span></span><br><span class="line">                    <span class="keyword">continue</span> restartFromHead;</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                    p = q; <span class="comment">// 往后移动，继续找</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 和上面的逻辑基本一致</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> E <span class="title function_">peek</span><span class="params">()</span> &#123;</span><br><span class="line">        restartFromHead:</span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; h = head, p = h, q;;) &#123;</span><br><span class="line">                <span class="type">E</span> <span class="variable">item</span> <span class="operator">=</span> p.item;</span><br><span class="line">                <span class="keyword">if</span> (item != <span class="literal">null</span> || (q = p.next) == <span class="literal">null</span>) &#123;</span><br><span class="line">                    updateHead(h, p); <span class="comment">// updateHead 自身也做了一次 h 是否等于 p 的判断的</span></span><br><span class="line">                    <span class="keyword">return</span> item;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (p == q)</span><br><span class="line">                    <span class="keyword">continue</span> restartFromHead;</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                    p = q;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 返回列表中的第一个活动（未删除）节点，如果没有，则返回 null。</span></span><br><span class="line">    <span class="comment">// 这是 poll/peek 的另一种变体； 这里返回第一个节点，而不是元素。 </span></span><br><span class="line">    <span class="comment">// 作为类内的方法使用，不公开</span></span><br><span class="line">    Node&lt;E&gt; <span class="title function_">first</span><span class="params">()</span> &#123;</span><br><span class="line">        restartFromHead:</span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; h = head, p = h, q;;) &#123;</span><br><span class="line">                <span class="type">boolean</span> <span class="variable">hasItem</span> <span class="operator">=</span> (p.item != <span class="literal">null</span>);</span><br><span class="line">                <span class="keyword">if</span> (hasItem || (q = p.next) == <span class="literal">null</span>) &#123;</span><br><span class="line">                    updateHead(h, p);</span><br><span class="line">                    <span class="keyword">return</span> hasItem ? p : <span class="literal">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (p == q)</span><br><span class="line">                    <span class="keyword">continue</span> restartFromHead;</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                    p = q;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 不是通过 size == 0 来判断的</span></span><br><span class="line">    <span class="comment">// 时间复杂度: O(1)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">isEmpty</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> first() == <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 需要遍历整个链表，因为没有成员属性记录元素个数</span></span><br><span class="line">    <span class="comment">// 时间复杂度: O(n), 谨慎使用</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">size</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (Node&lt;E&gt; p = first(); p != <span class="literal">null</span>; p = succ(p)) <span class="comment">// 注意是 succ(p) 而不是简单的 p.next</span></span><br><span class="line">            <span class="keyword">if</span> (p.item != <span class="literal">null</span>)</span><br><span class="line">                <span class="keyword">if</span> (++count == Integer.MAX_VALUE)</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">remove</span><span class="params">(Object o)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (o != <span class="literal">null</span>) &#123;</span><br><span class="line">            Node&lt;E&gt; next, pred = <span class="literal">null</span>;</span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; p = first(); p != <span class="literal">null</span>; pred = p, p = next) &#123;</span><br><span class="line">                <span class="type">boolean</span> <span class="variable">removed</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">                <span class="type">E</span> <span class="variable">item</span> <span class="operator">=</span> p.item;</span><br><span class="line">                <span class="keyword">if</span> (item != <span class="literal">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (!o.equals(item)) &#123;</span><br><span class="line">                        next = succ(p);</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    removed = p.casItem(item, <span class="literal">null</span>);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                next = succ(p);</span><br><span class="line">                <span class="keyword">if</span> (pred != <span class="literal">null</span> &amp;&amp; next != <span class="literal">null</span>) <span class="comment">// unlink</span></span><br><span class="line">                    pred.casNext(p, next); <span class="comment">// cas 失败也 ok</span></span><br><span class="line">                <span class="keyword">if</span> (removed)</span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">checkNotNull</span><span class="params">(Object v)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (v == <span class="literal">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>();</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * UNSAFE 的 cas </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">casTail</span><span class="params">(Node&lt;E&gt; cmp, Node&lt;E&gt; val)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> UNSAFE.compareAndSwapObject(<span class="built_in">this</span>, tailOffset, cmp, val);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">casHead</span><span class="params">(Node&lt;E&gt; cmp, Node&lt;E&gt; val)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> UNSAFE.compareAndSwapObject(<span class="built_in">this</span>, headOffset, cmp, val);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Unsafe mechanics</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> sun.misc.Unsafe UNSAFE;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> headOffset;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> tailOffset;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            UNSAFE = sun.misc.Unsafe.getUnsafe();</span><br><span class="line">            Class&lt;?&gt; k = ConcurrentLinkedQueue.class;</span><br><span class="line">            headOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                (k.getDeclaredField(<span class="string">&quot;head&quot;</span>));</span><br><span class="line">            tailOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                (k.getDeclaredField(<span class="string">&quot;tail&quot;</span>));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JUC/" rel="tag"># JUC</a>
              <a href="/tags/%E5%B9%B6%E5%8F%91%E9%9B%86%E5%90%88%E7%B1%BB/" rel="tag"># 并发集合类</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/12/15/BlockingQueue/" rel="prev" title="JDK的BlockingQueue">
                  <i class="fa fa-chevron-left"></i> JDK的BlockingQueue
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/12/15/CopyOnWriteArrayList%E5%92%8CCopyOnWriteArraySet/" rel="next" title="CopyOnWriteArrayList和CopyOnWriteArraySet">
                  CopyOnWriteArrayList和CopyOnWriteArraySet <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
